import React from 'react';
import { Table, Button, Modal, Input, message, Pagination, Select, Checkbox, TreeSelect } from 'antd';
import './recommend.less';
import $ from 'jquery';
import Config from '../../common/config';

const config = new Config();
const InputGroup = Input.Group;
const Option = Select.Option;
const token = sessionStorage.getItem('token')

export default class Recommendproduct extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			productlist: [],//全部商品列表
			productcount: 0,//全部商品条数
			pagesize: 10,// 每页显示的页数
			pageindex: 1,// 当前页
			keyWord: '',//关键字
			categoryid: undefined,//分类   
			categoryData: [], //所有分类  
			checkedProducts: undefined, //选择的商品 
		}
	}
	componentDidMount() {
		this.getProductList();
		this.getCategory();
	}
	//商品列表
	getProductList() {
		$.ajax({
			url: `${config.JuseProduct}/products/list`,
			type: "get",
			headers: {
				'Authorization': 'Bearer ' + token,
			},
			data: {
				pageSize: this.state.pagesize,
				page: this.state.pageindex,
				inKey: this.state.keyWord,//关键字
				categoryId: this.state.categoryid,//分类
				saleStatus: 1,
			},
			async: true,
			success: res => {
				if (res.code === 200) {
					let length = res.data.rows.length;
					this.setState({
						productlist: res.data.rows,
						productcount: res.data.count,
					});
				}
			}
		});
	}
	//分类列表
	getCategory() {
		$.ajax({
			url: `${config.JuseProduct}/categories/getCategoriesTree`,
			type: "get",
			headers: {
				'Authorization': 'Bearer ' + token,
			},
			async: true,
			success: res => {
				console.log('分类列表', res);
				if (res.code === 200) {
					const data = res.data;
					const loop = list => {
						list.forEach(item => {
							item.key = item.categoryCode
							item.value = item.categoryCode
							item.label = item.categoryRename || item.categoryName
							if (item.son) {
								item.children = item.son
								loop(item.children)
							}
						})
					}
					loop(res.data)
					this.setState({
						categoryData: data,
					});
				}
			}
		});
	}
	//输入搜索关键字
	changeInkey(e) {
		this.setState({
			keyWord: e.target.value
		})
	}
	//选择分类
	changeCategory(value) {
		this.setState({
			categoryid: value
		})
	}
	//搜索
	searchProduct() {
		this.setState({
			pageindex: 1
		}, () => this.getProductList())
	}
	//重置
	clearSearch() {
		this.setState({
			keyWord: "",
			categoryid: undefined,
		})
	}
	// 分页
	changePage(pageindex) {
		this.setState({
			pageindex
		}, () => {
			this.getProductList();
		});
	}
	//选择商品
	selectProduct(text, record, e) {
		const { products } = this.props;
		let { checkedProducts } = this.state;
		if (!checkedProducts) {
			checkedProducts = products;
		}
		if (e.target.checked) {
			if (checkedProducts.length < 8) {
				checkedProducts.push(record);
			}
		} else {
			for (let i = 0, len = checkedProducts.length; i < len; i++) {
				if (checkedProducts[i]) {
					if (checkedProducts[i].productId == text) {
						checkedProducts.splice(i, 1);
						break;
					}
				}
			}
		}
		this.setState({
			checkedProducts
		})
	}
	//确认添加
	handleOK() {
		let { checkedProducts } = this.state;
		const { addProduct, products } = this.props;
		if (!checkedProducts) {
			checkedProducts = products;
		}
		if (addProduct) {
			addProduct(checkedProducts);
			this.setState({
				checkedProducts: undefined,
			});
		}
	}
	//取消
	handleCancel() {
		const { cancelProduct } = this.props;
		if (cancelProduct) {
			cancelProduct();
			this.setState({
				checkedProducts: undefined,
			});
		}
	}
	//关闭对话框后重置状态
	resetModal() {
		this.setState({
			pageindex: 1,
			keyWord: '',
			categoryid: undefined,
		}, () => this.getProductList())
	}
	render() {
		let checkedProductId = [];
		{
			this.state.checkedProducts ? this.state.checkedProducts.forEach((val, i) => {
				if (val) {
					checkedProductId.push(val.productId)
				}
			}) :
				this.props.products.forEach((val, i) => {
					if (val) {
						checkedProductId.push(val.productId)
					}
				})
		}
		const columns = [{
			title: '勾选',
			dataIndex: 'productId',
			width: '5%',
			render: (text, record) => {
				return <Checkbox
					onChange={this.selectProduct.bind(this, text, record)}
					checked={checkedProductId.indexOf(text) == -1 ? false : true}
					disabled={checkedProductId.length < 8 ? false : (checkedProductId.indexOf(text) == -1 ? true : false)}
				></Checkbox>
			}
		}, {
			title: '药品名称',
			dataIndex: 'productName',
			width: '25%',
		}, {
			title: '药品图片',
			dataIndex: '',
			width: '10%',
			render: (text, record) => {
				return <img src={record.imageUrl + record.listImage} style={{ width: "40px" }} />
			}
		}, {
			title: '通用名',
			dataIndex: 'genericName',
			width: '15%',
		}, {
			title: '规格',
			dataIndex: 'specifications',
			width: '10%',
		}, {
			title: '品牌',
			dataIndex: 'brandName',
			width: '15%',
		}, {
			title: '生产厂家',
			dataIndex: 'manufacturer',
			width: '20%',
		}];
		return (
			<Modal
				className="floor-pmodal"
				title="已上架商品列表"
				visible={this.props.visible}
				okText={"确认添加"}
				onOk={() => this.handleOK()}
				onCancel={() => this.handleCancel()}
				maskClosable={false}
				afterClose={() => this.resetModal()}
			>
				<div className='member-content-Search clearfix'>
					<div className='addetd addetd-b'>
						<Input className='addetd-a-r' addonBefore="药品名/通用名/标签" placeholder="请输入" value={this.state.keyWord} onChange={(e) => this.changeInkey(e)} />
					</div>
					<div className='addetd addetd-a'>
						<InputGroup compact>
							<Input addonBefore="类 别" />
							<TreeSelect
								style={{ width: 150 }}
								value={this.state.categoryid}
								dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
								treeData={this.state.categoryData}
								placeholder="请选择"
								treeDefaultExpandAll
								onChange={(value) => this.changeCategory(value)}
							/>
						</InputGroup>
					</div>
					<Button type="primary" className='member-button' icon="search" onClick={this.searchProduct.bind(this)}>搜索</Button>
					<Button type="primary" className='member-button' icon="reload" onClick={this.clearSearch.bind(this)}>重置</Button>
				</div>
				<div className='allgoods-table clearfix floor-ptable'>
					<Table
						rowKey="productId"
						columns={columns}
						dataSource={this.state.productlist}
						pagination={false}
						bordered
					/>
				</div>
				<div className="floor-ppagi">
					<p className="floor-ppagip">
						当前显示
                        {this.state.pagesize * (this.state.pageindex - 1) + 1}—
                        {this.state.pagesize * this.state.pageindex < this.state.productcount ? this.state.pagesize * this.state.pageindex : this.state.productcount}条记录，
                        共{this.state.productcount}条记录
                    </p>
					<Pagination current={this.state.pageindex} total={this.state.productcount} defaultPageSize={this.state.pagesize} onChange={this.changePage.bind(this)} />
				</div>
			</Modal>
		)
	}
}